function hfile = vmr_MaskWithVMR(hfile, maskvmr, thold)
% VMR::MaskWithVMR  - set voxels 0 where mask VMR below threshold
%
% FORMAT:       [vmr] = vmr.MaskWithVMR(maskvmr [, threshold])
%
% Input fields:
%
%       maskvmr     masking VMR object
%       threshold   threshold value, default: 11
%
% Output fields:
%
%       vmr         masked VMR

% Version:  v0.7b
% Build:    7090217
% Date:     Sep-02 2007, 5:40 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'vmr') || ...
    numel(maskvmr) ~= 1 || ...
   ~isBVQXfile(maskvmr, 'vmr')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end
bc1 = bvqxfile_getcont(hfile.L);
bc2 = bvqxfile_getcont(maskvmr.L);
if any(size(bc1.VMRData) ~= size(bc2.VMRData))
    error( ...
        'BVQXfile:InvalidObject', ...
        'Dimension mismatch.' ...
    );
end
if nargin < 3 || ...
   ~isnumeric(thold) || ...
    numel(thold) ~= 1 || ...
    isnan(thold)
    thold = 11;
else
    if thold < 0
        thold = 0;
    elseif bc2.VMR8bit && ...
        thold > 225
        thold = 226;
    elseif thold > 32767
        thold = 32768;
    end
end
thold = fix(thold);

% resolve transio first
if istransio(bc1.VMRData)
    bc1.VMRData = bc1.VMRData(:, :, :);
end
if istransio(bc1.VMRData16)
    bc1.VMRData16 = bc1.VMRData16(:, :, :);
end

% apply mask
msk = (bc2.VMRData < thold);
bc1.VMRData(msk) = 0;
if numel(bc1.VMRData16) == numel(msk)
    bc1.VMRData16(msk) = 0;
end
bvqxfile_setcont(hfile.L, bc1);
